package com.bao.wechat.coin.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.bao.wechat.activity.entity.XtjActivity;
import com.bao.wechat.activity.service.IXtjActivityService;
import com.bao.wechat.coin.entity.XtjCoin;
import com.bao.wechat.coin.service.IXtjCoinService;
import com.bao.wechat.files.entity.XtjFiles;
import com.bao.wechat.utils.ExcelUtil;
import com.bao.wechat.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * <p>
 *  前端控制器
 * </p> 
 *
 * @author bao
 */

@RestController
@RequestMapping(value = "/xtjCoin", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class XtjCoinController extends ApiController {

	@Autowired
	IXtjActivityService iXtjActivityService;
	@Autowired
	IXtjCoinService iXtjCoinService;

	/**
	 * 导入兑换券并生成任务
	 * @param request
	 * @param model
	 * @return
	 * @throws ParseException
	 * @throws FileNotFoundException
	 */
	@ResponseBody 
	@RequestMapping(value = "/toXls")
	public R toXls(HttpServletRequest request, Model model, @RequestParam(required = false) MultipartFile file,Integer code) throws IOException, ParseException {

		if (file.isEmpty() != true) {

			//保存课程
			XtjActivity xtjActivity =new XtjActivity();
			xtjActivity.setName(file.getOriginalFilename());
			xtjActivity.setCode(code);
			iXtjActivityService.save(xtjActivity);

			InputStream stream = file.getInputStream();
			try {
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(stream);
				//XSSFWorkbook hssfWorkbook = new  XSSFWorkbook(stream);
				// 循环工作表Sheet
				for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
					HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
					if (hssfSheet == null) {
						continue;
					}

					// 循环行Row
					for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
						HSSFRow hssfRow = hssfSheet.getRow(rowNum);
						if (hssfRow != null) {
							XtjCoin xtjCoin = new XtjCoin();
							DateTimeFormatter df=  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

							xtjCoin.setAid(xtjActivity.getId());
							//优惠券名称
							String name = getValue(hssfRow.getCell(0));
							xtjCoin.setName(name);

							//开始时间
							Date start_time= hssfRow.getCell(1).getDateCellValue();
							System.out.println(start_time);
							xtjCoin.setStartTime(start_time);

							//结束时间
							Date end_time= hssfRow.getCell(2).getDateCellValue();
							xtjCoin.setEndTime(end_time);

							//兑换码
							String coin= getValue(hssfRow.getCell(3));
							xtjCoin.setCoin(coin);

							//是否使用
							String status= getValue(hssfRow.getCell(4));
							xtjCoin.setStatus(status);

							//使用时间

							//                                Date use_time= hssfRow.getCell(5).getDateCellValue();
							//                                xtjCoin.setUseTime(use_time);

							//兑换人id
							//                                String user_id= getValue(hssfRow.getCell(6));
							//                                xtjCoin.setUserId(Integer.parseInt(user_id));

							//兑换人姓名
							//                                String user_name= getValue(hssfRow.getCell(7));
							//                                xtjCoin.setUserName(user_name);
							xtjCoin.setCreatedAt(new Date());
							iXtjCoinService.save(xtjCoin);


						}
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return R.ok().put("data", "导入成功");
		}
		return R.error();
	}

	/**
	 * 任务中导入03版本兑换券Excel
	 * @param request
	 * @param model
	 * @return
	 * @throws ParseException
	 * @throws FileNotFoundException
	 */
	@ResponseBody
	@RequestMapping(value = "/toTaskXls")
	public R toTaskXls(HttpServletRequest request, Model model, @RequestParam(required = false) MultipartFile file,Integer aid) throws IOException, ParseException {

		if (file.isEmpty() != true) {



			InputStream stream = file.getInputStream();
			try {
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(stream);
				//XSSFWorkbook hssfWorkbook = new  XSSFWorkbook(stream);
				// 循环工作表Sheet
				for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
					HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
					if (hssfSheet == null) {
						continue;
					}

					// 循环行Row
					for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
						HSSFRow hssfRow = hssfSheet.getRow(rowNum);
						if (hssfRow != null) {
							XtjCoin xtjCoin = new XtjCoin();
							DateTimeFormatter df=  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

							xtjCoin.setAid(aid);
							//优惠券名称
							String name = getValue(hssfRow.getCell(0));
							xtjCoin.setName(name);

							//开始时间
							Date start_time= hssfRow.getCell(1).getDateCellValue();
							xtjCoin.setStartTime(start_time);

							//结束时间
							Date end_time= hssfRow.getCell(2).getDateCellValue();
							xtjCoin.setEndTime(end_time);

							//兑换码
							String coin= getValue(hssfRow.getCell(3));
							xtjCoin.setCoin(coin);

							//是否使用
							String status= getValue(hssfRow.getCell(4));
							xtjCoin.setStatus(status);

							//使用时间

							//                                Date use_time= hssfRow.getCell(5).getDateCellValue();
							//                                xtjCoin.setUseTime(use_time);

							//兑换人id
							//                                String user_id= getValue(hssfRow.getCell(6));
							//                                xtjCoin.setUserId(Integer.parseInt(user_id));

							//兑换人姓名
							//                                String user_name= getValue(hssfRow.getCell(7));
							//                                xtjCoin.setUserName(user_name);
							xtjCoin.setCreatedAt(new Date());

							iXtjCoinService.save(xtjCoin);


						}
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return R.ok().put("data", "导入成功");
		}
		return R.error();
	}

	/**
	 * 任务中导出03版本兑换券Excel
	 * @param request
	 * @param model
	 * @return
	 * @throws ParseException
	 * @throws FileNotFoundException
	 */
	@ResponseBody
	@RequestMapping(value = "/deriveXls")
	public R deriveXls(Integer aid) throws IOException, ParseException {

		System.out.println("来啦");
		return R.error();
	}

	@SuppressWarnings("static-access")
	private String getValue(HSSFCell hssfCell) {
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		}else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			// 返回数值类型的值
			return String.valueOf(hssfCell.getNumericCellValue());
		} else {
			// 返回字符串类型的值
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}

	/**
	 * 第一次验证时绑定openid  第二次请求是 对比openid
	 * @param aid
	 * @param coin
	 * @param openid
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getCoin")
	public R getCoin(Integer aid,String coin,String openid){
		QueryWrapper<XtjCoin> queryWrapper = new QueryWrapper<XtjCoin>();
		queryWrapper.eq("aid",aid);
		queryWrapper.eq("coin",coin);

		XtjCoin xtjCoin = iXtjCoinService.getOne(queryWrapper);
		if (xtjCoin==null){
			return  R.error(405,"活动已结束！");
		}
		if (xtjCoin.getOpenid()==null){
			xtjCoin.setStatus("已使用");
			xtjCoin.setUpdatedAt(new Date());
			xtjCoin.setOpenid(openid);
			iXtjCoinService.updateById(xtjCoin);
			return  R.ok();
		}else if(xtjCoin.getOpenid().equals(openid)){
			return  R.ok();
		}else if(!xtjCoin.getOpenid().equals(openid)){
			return  R.error(400,"请过任务后得到兑换券");
		}
		return  R.ok();
	}

	/**
	 * 查询兑换券列表
	 * @param aid
	 * @param coin
	 * @param openid
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getCoinList")
	public R getCoinList(Integer aid, Integer page, Integer limit){
		Page p = new Page<XtjFiles>(page,limit);
		QueryWrapper<XtjCoin> queryWrapper = new QueryWrapper<XtjCoin>();
		queryWrapper.eq("aid",aid);
		List<XtjCoin> list = iXtjCoinService.page(p,queryWrapper).getRecords();
		return  R.ok().put("data", list).put("count", iXtjCoinService.count(queryWrapper));
	}

	/**
	 * 导出兑换券
	 * @return
	 */
	@RequestMapping(value = "/export")
	public void export(HttpServletRequest request,HttpServletResponse response,Integer aid) throws Exception {
		try {
			ServletOutputStream out = response.getOutputStream();
			String[] headers = { };
			ExcelUtil eeu = new ExcelUtil();
			HSSFWorkbook workbook = new HSSFWorkbook();
			
			QueryWrapper<XtjCoin> queryWrapper = new QueryWrapper<XtjCoin>();
			queryWrapper.eq("aid",aid);
			List<XtjCoin> list = iXtjCoinService.list(queryWrapper);
			XtjActivity activity = iXtjActivityService.getById(aid);
			List<List<String>> data = new ArrayList<List<String>>();
			
				
				for (XtjCoin coin : list) {
					List rowData = new ArrayList();
					rowData.add(coin.getCoin());
					data.add(rowData);
				}
				
			eeu.exportExcel(workbook, 0, activity.getName(), headers, data, out,aid);
			setResponseHeader(response, activity.getName());
			workbook.write(out);
			out.close();


		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//发送响应流方法
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			//response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
